package com.yx.cloud.network.ap;


import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;

import com.iot.common.utils.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;

public class TcpServer {
    public static String HOST = "192.168.137.1";
    public static int PORT = 58725;
    private static Socket mSocket = null;
    private static OutputStream mOutStream = null;
    private static InputStream mInStream = null;
    private static Context mContext;

    TcpServer(Context context) {
        mContext = context;
    }

    @SuppressLint("ServiceCast")
    public static boolean startClient(Context context, String host, int port) {
        LogUtils.i("AP  配网 startClient ：" + host + " , " + port);
        mSocket = new Socket();
        if (mSocket != null && mSocket.isConnected()) {
            try {
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        setBindSocket(context);//给socket进行网络通道绑定
        try {
            Thread.sleep(1500);
            mSocket.bind(null);
            LogUtils.i("AP 配网 host : " + host + " , port : " + port);
            //指定ip地址和端口号
            mSocket.connect(new InetSocketAddress(host, port), 3000);
            if (mSocket != null && mSocket.isConnected()) {
                LogUtils.i("AP 配网 startClient 连接成功");
                //获取输出流、输入流
                mInStream = mSocket.getInputStream();
                mOutStream = mSocket.getOutputStream();
                return true;
            } else {
                LogUtils.i("AP 配网 startClient 连接失败");
            }
        } catch (Exception e) {
            LogUtils.i("AP 配网 Exception " + e.toString());
            e.printStackTrace();
            return false;
        }
        return false;
    }

    private static void setBindSocket(Context context) {
        final ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder request = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        connManager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                try {
                    network.bindSocket(mSocket);
                    LogUtils.i("AP 配网  bind network " + network.toString());
                } catch (IOException e) {
                    LogUtils.i("AP 配网  bind network 异常");
                    e.printStackTrace();
                }
            }

            @Override
            public void onLost(Network network) {
                try {
                    connManager.unregisterNetworkCallback(this);
                } catch (SecurityException e) {
                    LogUtils.i("AP 配网  Failed to unregister network callback");
                }
            }
        });
    }


    //发送数据
    public static void writeMsg(List<ApDataPacket> dataPackets) throws IOException, InterruptedException {
        for (int i = 0; i < dataPackets.size(); i++) {
            LogUtils.ls("AP 配网 writeMsg 发送数据 ：" + dataPackets.get(i).packData.length);
            mOutStream.write(dataPackets.get(i).packData);
            mOutStream.flush();
            Thread.sleep(500);
        }
//        dataPacketsSize = 0;
//        while (true) {
//            if (dataPacketsSize < dataPackets.size() && isReadData) {
//                isReadData = false;
//                LogUtils.ls("AP 配网 writeMsg 发送数据 ：" + dataPackets.get(dataPacketsSize).packData.length);
//                mOutStream.write(dataPackets.get(dataPacketsSize).packData);
//                mOutStream.flush();
//            }
//        }
    }


//    public static class ReadThread extends Thread {
//        @Override
//        public void run() {
//            int size;
//            byte[] buffer = new byte[1024];
//            try {
//                while ((size = mInStream.read(buffer)) != -1) {
//                    String str = new String(buffer, 0, size);
//                    LogUtils.i("配网 收到来自服务器的消息: " + str);
//                    if (str.length() > 0) {
//                        isReadData = true;
//                    } else {
//                        isReadData = false;
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    //关闭Socket
    public static void closeConnection() {
//        if (readThread != null) {
//            readThread.interrupt();
//        }
        try {
            if (mOutStream != null) {
                mOutStream.close(); //关闭输出流
                mOutStream = null;
            }
            if (mInStream != null) {
                mInStream.close(); //关闭输入流
                mInStream = null;
            }
            if (mSocket != null) {
                mSocket.close();  //关闭socket
                mSocket = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
